/*
 * 2021/12/17	9:47
 *
 *	linux二进制分析	P121
 */

/*
 * 对 mmap 系统调用的封装，使用了 C 语言和内联汇编
 */
#include <stdio.h>
#include <stddef.h>
#include <sys/mman.h>


#define __NR_MMAP 9 

void *_mmap(unsigned long addr, unsigned long len, unsigned long prot, 
unsigned long flags, long fd, unsigned long off)  
{  
   long mmap_fd = fd;  
   unsigned long mmap_off = off;  
   unsigned long mmap_flags = flags;  
   unsigned long ret;  

   __asm__ volatile( 
                    "mov %0, %%rdi\n"  
                    "mov %1, %%rsi\n"  
                    "mov %2, %%rdx\n"  
                    "mov %3, %%r10\n"  
                    "mov %4, %%r8\n"  
                    "mov %5, %%r9\n"  
                    "mov $__NR_MMAP, %%rax\n"  
                    "syscall\n" : : "g"(addr), "g"(len),  
                    "g"(prot),                "g"(flags),  
                    "g"(mmap_fd), "g"(mmap_off));  
   __asm__ volatile ("mov %%rax, %0" : "=r"(ret));  
   return (void *)ret;  
}  

void * _malloc(size_t len)  
{  
   void *mem = _mmap(NULL, len, PROT_READ|PROT_WRITE,  
     MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);  
     if (mem == (void *)-1)  
             return NULL;  
     return mem;  
}  
 
void main()
{
    
}

/* 
gcc -nostdlib -o 01 01.c
gcc -nostdlib -o 01 01.c -no-pie
gcc -nostdlib -o 01 01.c -fpic


*/


